import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, logout } from '@/api/user'
import { getPermissionCodesByUserId, getUserMenuTree } from '@/api/permission'

// 用户模块
export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userId: null,
    userName: '',
    name: '',
    avatar: '',
    permissions: [], // 用户权限列表
    menus: [] // 用户菜单列表
  }),
  getters: {
    hasToken: (state) => !!state.token
  },
  actions: {
    // 登录
    async login(userInfo) {
      try {
        const { username, password } = userInfo
        const response = await login({ username, password })

        if (response.data.code === 1) {
          const { token, id, userName, name } = response.data.data

          this.token = token
          this.userId = id
          this.userName = userName
          this.name = name

          setToken(token)

          // 保存用户基本信息到localStorage，以便刷新页面后恢复
          localStorage.setItem(
            'user_info',
            JSON.stringify({
              id,
              userName,
              name
            })
          )

          // 获取用户权限
          await this.getPermissions()

          // 获取用户菜单
          await this.getMenus()

          return Promise.resolve(response.data)
        }
        return Promise.reject(response.data)
      } catch (error) {
        console.error('登录失败:', error)
        return Promise.reject(error)
      }
    },
    // 获取用户权限
    async getPermissions() {
      try {
        if (!this.userId) {
          const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}')
          if (userInfo.id) {
            this.userId = userInfo.id
            this.userName = userInfo.userName || ''
            this.name = userInfo.name || ''
          } else {
            return []
          }
        }

        const response = await getPermissionCodesByUserId(this.userId)

        if (response.data && response.data.code === 1) {
          const permissions = response.data.data || []

          // 清空原有权限并添加新权限
          this.permissions = [...permissions]

          // 同时保存到localStorage，确保刷新页面后能恢复
          localStorage.setItem('user_permissions', JSON.stringify(permissions))

          return permissions
        }
        return []
      } catch (error) {
        console.error('获取权限失败:', error)
        // 尝试从localStorage恢复权限
        this.initPermissions()
        return this.permissions
      }
    },

    // 获取用户菜单
    async getMenus() {
      try {
        const response = await getUserMenuTree()

        if (response.data && response.data.code === 1) {
          const menus = response.data.data || []

          // 清空原有菜单并添加新菜单
          this.menus = [...menus]

          // 同时保存到localStorage，确保刷新页面后能恢复
          localStorage.setItem('user_menus', JSON.stringify(menus))

          return menus
        }
        return []
      } catch (error) {
        console.error('获取菜单失败:', error)
        // 尝试从localStorage恢复菜单
        this.initMenus()
        return this.menus
      }
    },

    // 退出登录
    async logout() {
      try {
        await logout()
        this.token = ''
        this.userId = null
        this.userName = ''
        this.name = ''
        this.permissions = []
        this.menus = []
        removeToken()
        localStorage.removeItem('user_info')
        localStorage.removeItem('user_permissions')
        localStorage.removeItem('user_menus')
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.userId = null
      this.userName = ''
      this.name = ''
      this.permissions = []
      this.menus = []
      removeToken()
      localStorage.removeItem('user_info')
      localStorage.removeItem('user_permissions')
      localStorage.removeItem('user_menus')
    },

    // 初始化权限数据，从localStorage恢复
    initPermissions() {
      try {
        const savedPermissions = localStorage.getItem('user_permissions')
        if (savedPermissions) {
          const permissions = JSON.parse(savedPermissions)
          this.permissions = [...permissions]
          return true
        }
      } catch (e) {
        console.error('恢复权限失败:', e)
      }
      return false
    },

    // 初始化菜单数据，从localStorage恢复
    initMenus() {
      try {
        const savedMenus = localStorage.getItem('user_menus')
        if (savedMenus) {
          const menus = JSON.parse(savedMenus)
          this.menus = [...menus]
          return true
        }
      } catch (e) {
        console.error('恢复菜单失败:', e)
      }
      return false
    },

    // 强制刷新权限
    async refreshPermissions() {
      // 清除缓存
      localStorage.removeItem('user_permissions')
      // 重新获取权限
      return await this.getPermissions()
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user_store',
        storage: localStorage,
        paths: ['token', 'userId', 'userName', 'name']
        // 不包含permissions和menus，我们手动管理它们
      }
    ]
  }
})
